package com.ruoyi.crm.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.excel.core.ExcelResult;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.crm.domain.ContactInfo;
import com.ruoyi.crm.domain.CustomerInfo;
import com.ruoyi.crm.service.IContactService;
import com.ruoyi.crm.service.ICustomerService;

import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 客户列表控制层
 * @author  dxy
 *
 */

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/customer")
public class CustomerInforCntroller extends BaseController {

    private final ICustomerService customerService;

    private final IContactService contactService;

    /**
     * 查询客户列表
     */
    @SaCheckPermission("customer:customerInfo:list")
    @GetMapping("/list")
    public TableDataInfo<CustomerInfo> list(CustomerInfo customerInfo, PageQuery pageQuery) {
        //先查询整个列表
        TableDataInfo<CustomerInfo> list= customerService.selectCustomerPageList(customerInfo, pageQuery);
        //将列表进行遍历
        list.getRows().forEach(C->{
            if(C.getCustomerId()!=null){
                //看contcatInfo表中是否存在getContactId()，相当于customerInfo中的外键，存在及查出来想要的数据输出
                ContactInfo contactInfo=contactService.selectContactById(C.getContactId());
                if(contactInfo!=null){
                    C.getParams().put("email",contactInfo.getEmail());
                    C.getParams().put("phone",contactInfo.getPhone());
                    C.getParams().put("address",contactInfo.getAddress());
                    C.getParams().put("landlineNumber",contactInfo.getLandlineNumber());
                }
            }
        });
        return list;
    }
    /**
     * 根据客户ID获取详细信息
     *
     * @param customerId 客户ID
     */
    @SaCheckPermission("customer:customerInfo:query")
    @GetMapping(value = "/{customerId}")
    public R<CustomerInfo> getInfo(@PathVariable Long customerId) {
        return R.ok(customerService.selectCustomerById(customerId));
    }

    /**
     * 新增客户列表
     */
    @SaCheckPermission("customer:customerInfo:add")
    @Log(title = "客户列表",businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void>  add(@Validated @RequestBody CustomerInfo customerInfo) {
        return toAjax(customerService.insertCustomer(customerInfo));
    }
    /**
     * 修改客户列表
     */
    @SaCheckPermission("customer:customerInfo:edit")
    @Log(title = "客户列表",businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void>  edit(@Validated @RequestBody CustomerInfo customerInfo) {
        return toAjax(customerService.updateCustomer(customerInfo));

    }

    /**
     * 删除客户列表
     */
    @SaCheckPermission("customer:customerInfo:remove")
    @Log(title = "客户列表",businessType = BusinessType.DELETE)
    @DeleteMapping("/{customerId}")
    public R<Void> Remove(@PathVariable Long customerId){
        return toAjax(customerService.delectCustomer(customerId));


    }

    /**
     * 导入数据
     *
     * @param file 导入文件
     * @param
     */
    @Log(title = "客户列表", businessType = BusinessType.IMPORT)
    @SaCheckPermission("customer:customerInfo:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file")MultipartFile file) throws Exception {

//        //导入方法,未封装的EasyExcel方法。使用@ExcelProperty注解，转换成输入流。
//        List<CustomerInfo> list = EasyExcel.read(file.getInputStream())
//            .head(CustomerInfo.class)
//            .sheet()
//            .doReadSync();
////        System.out.println("读取到数据条数：" + (list == null ? 0 : list.size()));
////        list.forEach(System.out::println);
//        boolean saved = customerService.insertBatch(list);
//        if (!saved) {
//            return R.fail("导入失败，保存数据库时出错");
//        }
//        return R.ok("成功导入客户数据：" + list.size() + " 条");

        //框架封装好的导入方法ExcelUtil，进行导入
        //1. ExcelResult为范型
        ExcelResult<CustomerInfo> result = ExcelUtil.importExcel(file.getInputStream(), CustomerInfo.class, false);
        //2.将范型转换为list
        List<CustomerInfo> dataList = result.getList();
        //3.新增到数据库
        boolean saved = customerService.insertBatch(dataList);
        if (!saved) {
            return R.fail("导入失败，保存数据库时出错");
        }
        return R.ok(result.getAnalysis());

    }

    /**
     * 导出用户列表
     */
    @Log(title = "客户列表", businessType = BusinessType.EXPORT)
    @SaCheckPermission("customer:customerInfo:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustomerInfo customerInfo){
        List<CustomerInfo> list = customerService.selectCustomerList(customerInfo);
        List<CustomerInfo> listVo= BeanUtil.copyToList(list,CustomerInfo.class);
        ExcelUtil.exportExcel(list, "客户列表数据",CustomerInfo.class, response);
    }

    /**
     * 获取客户名称下拉列表
     */
    @GetMapping("/customers/options")
    public R<List<CustomerInfo>> getCustomerOptions() {
        // 1. 查询所有客户信息
        List<CustomerInfo> customers = customerService.selectCustomerList(new CustomerInfo());
        //2.转换成stream流，可以不写
        List<CustomerInfo> options = customers.stream()
            .map(c -> {
                CustomerInfo info = new CustomerInfo();
                info.setCustomerId(c.getCustomerId());
                info.setCustomerName(c.getCustomerName());
                return info;
            })
            .collect(Collectors.toList());
        return R.ok(options);
    }

}
